<title>
public
Folder
public
Folder
.env
<meta>
Tags on the Server
npm start
doesn't detect
changes
npm test
hangs on macOS
Sierra
npm run build
exits too early
npm run build
fails on Heroku
npm run build
fails to minify
create-react-app
is a global command-line utility
that you use to create new
projects.
react-scripts
is a development dependency in
the generated projects
(including this one).
create-react-app
itself: it delegates all the setup to react-scripts.
create-react-app, it always creates the project with
the latest version of react-scripts
so you'll get all the new
features and improvements in newly
created apps automatically.
react-scripts, [open the changelog](https:
//github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md),
find the version you're currently
on (check package.json
in this folder if you're not
sure), and apply the migration
instructions for the newer
versions.
react-scripts
version in package.json
and running npm install
in this folder should be enough, but
it's good to consult the
[changelog](https:
//github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md)
for potential breaking changes.
react-scripts
painlessly.
public/index.html
is the page template;
src/index.js
is the JavaScript entry
point.
src. For faster rebuilds, only files
inside src
are processed by Webpack. You need to put any JS and CSS files inside src, otherwise Webpack won't see
them.
public
can be used from public/index.html. Read instructions below for using
assets from JavaScript and HTML.
npm start
npm test
npm run build
build
folder. It correctly bundles React in
production mode and optimizes the
build for the best performance.
npm run eject
eject, you can't go back!
eject
at any time. This command will remove
the single build dependency from your
project.
eject
will still work, but they will point
to the copied scripts so you can tweak
them. At this point you're on
your own.
eject. The curated feature set is suitable
for small and middle deployments, and
you shouldn't feel obligated to
use this feature. However we
understand that this tool
wouldn't be useful if you
couldn't customize it when you
are ready for it.
Object.assign()](https:
//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
via [object-assign](https:
//github.com/sindresorhus/object-assign).
Promise](https:
//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
via [promise](https:
//github.com/then/promise).
fetch()](https:
//developer.mozilla.org/en/docs/Web/API/Fetch_API)
via [whatwg-fetch](https:
//github.com/github/fetch).
Array.from()
or Symbol), make sure you are including the
appropriate polyfills manually, or
that the browsers you are targeting
already support them.
for...of
or [...nonArrayValue]
causes Babel to emit code that depends
on ES6 runtime features and might not
work without a polyfill. When in
doubt, use [Babel REPL](https:
//babeljs.io/repl/) to see what any
specific syntax compiles down
to.
Note: this feature is available with[email protected]and higher. It also only works with npm 3 or higher.
.eslintrc
to the project root:
.eslintrc
file further, these changes will only affect the editor
integration. They won't affect the terminal
and in-browser lint output. This is
because Create React App intentionally
provides a minimal set of rules that
find common mistakes.
launch.json
file and put it inside the .vscode
folder in your app's root
directory.
Note: the URL may be different if you've made adjustments via the HOST or PORT environment variables.
npm start, and start debugging in VS Code by
pressing F5
or by clicking the green debug icon.
You can now write code, set
breakpoints, make changes to the code,
and debug your newly modified code—all
from your editor.
Run
select Edit Configurations.... Then click +
and select JavaScript Debug. Paste http: //localhost:3000
into the URL field and save the
configuration.
Note: the URL may be different if you've made adjustments via the HOST or PORT environment variables.
npm start, then press ^D
on macOS or F9
on Windows and Linux or click the
green debug icon to start debugging in
WebStorm.
husky
makes it easy to use githooks as
if they are npm scripts.
lint-staged
allows us to run scripts on
staged files in git. See this
[blog post about lint-staged to
learn more about it](https:
//medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8).
prettier
is the JavaScript formatter we
will run before commits.
package.json
in the project root.
scripts
section:
package.json, for example:
./node_modules/.bin/prettier
--single-quote --write
"src/**/*.{js,jsx,json,css}"
to format your entire project for the
first time.
<title>
public
folder of the generated project. You
may edit the <title>
tag in it to change the title from
"React App" to anything
else.
public
folder very often. For example, adding
a stylesheet is done without touching
the HTML.
document.title](https:
//developer.mozilla.org/en-US/docs/Web/API/Document/title)
API. For more complex scenarios when
you want to change the title from
React components, you can use [React
Helmet](https:
//github.com/nfl/react-helmet), a
third party library.
npm:
react-router.
require()
and module.exports, we encourage you to use [import
and export](http:
//exploringjs.com/es6/ch_modules.html)
instead.
Button.js
DangerButton.js
export default Button
and import Button from
'./Button'.
import()](http:
//2ality.com/2017/01/import-operator.html#loading-code-on-demand).
Its [proposal](https:
//github.com/tc39/proposal-dynamic-import)
is in stage 3. The import()
function-like form takes the module
name as an argument and returns a
[Promise](https:
//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
which always resolves to the namespace
object of the module.
moduleA.js
App.js
moduleA.js
and all its unique dependencies as a
separate chunk that only loads after
the user clicks the 'Load'
button.
async
/ await
syntax if you prefer it.
import
beyond JavaScript. To express that a
JavaScript file depends on a CSS file,
you need to import the CSS from the JavaScript
file:
Button.css
Button.js
.css
file in the build output.
src/index.css. It would still be imported from src/index.js, but you could always remove that
import if you later migrate to a
different build tool.
.Button
CSS class in <AcceptButton>
and <RejectButton>
components, we recommend creating a <Button>
component with its own .Button
styles, that both <AcceptButton>
and <RejectButton>
can render (but [not inherit](https:
//facebook.github.io/react/docs/composition-vs-inheritance.html)).
package.json, add the following lines to scripts:
Note: To use a different preprocessor, replacebuild-cssandwatch-csscommands according to your preprocessor's documentation.
src/App.css
to src/App.scss
and run npm run watch-css. The watcher will find every Sass
file in src
subdirectories, and create a
corresponding CSS file next to it, in
our case overwriting src/App.css. Since src/App.js
still imports src/App.css, the styles become a part of your
application. You can now edit src/App.scss, and src/App.css
will be regenerated.
src/App.scss
and other component style files could
include @import
"./shared.scss";
with variable definitions.
--include-path
option to the command in package.json.
src/**/*.css
to your .gitignore
file. It is generally a good practice
to keep the build products outside of
the source control.
watch-css
automatically with npm start, and run build-css
as a part of npm run build. You can use the &&
operator to execute two scripts
sequentially. However, there is no
cross-platform way to run two scripts
in parallel, so we will install a
package for this:
start
and build
scripts to include the CSS
preprocessor commands:
npm start
and npm run build
also builds Sass files.
node-sass-chokidar?
node-sass
has been reported as having the
following issues:
node-sass --watch
has been reported to have performance issues
in certain conditions when used
in a virtual machine or with
docker.
node-sass
has been reported as having
issues with detecting new files
in a directory [#1891](https:
//github.com/sass/node-sass/issues/1891)
node-sass-chokidar
is used here as it addresses these
issues.
import
a file right in a JavaScript
module. This tells Webpack to include that
file in the bundle. Unlike CSS
imports, importing a file gives you a
string value. This value is the final
path you can reference in your code,
e.g. as the src
attribute of an image or the href
of a link to a PDF.
./) and replaces them with the final
paths from the compiled bundle. If you
make a typo or accidentally delete an
important file, you will see a
compilation error, just like when you
import a non-existent JavaScript
module. The final filenames in the
compiled bundle are generated by
Webpack from content hashes. If the
file content changes in the future,
Webpack will give it a different name
in production so you don't need
to worry about long-term caching of
assets.
public
Folder
Note: this feature is available with[email protected]and higher.
public
folder contains the HTML file so you
can tweak it, for example, to set the
page title. The <script>
tag with the compiled code will be
added to it automatically during the
build process.
public
folder.
import
assets in JavaScript files instead.
For example, see the sections on
adding a stylesheet and adding images
and fonts. This mechanism provides a
number of benefits:
public
folder, it will not
be processed by Webpack. Instead it
will be copied into the build folder
untouched. To reference assets in the public
folder, you need to use a special
variable called PUBLIC_URL.
index.html, you can use it like this:
public
folder will be accessible by %PUBLIC_URL%
prefix. If you need to use a file from src
or node_modules, you'll have to copy it there
to explicitly specify your intention
to make this file a part of the
build.
npm run build, Create React App will substitute %PUBLIC_URL%
with a correct absolute path so your
project works even if you use
client-side routing or host it at a
non-root URL.
process.env.PUBLIC_URL
for similar purposes:
public
folder get post-processed or
minified.
public
Folder
public
folder is useful as a workaround for a
number of less common cases:
manifest.webmanifest](https:
//developer.mozilla.org/en-US/docs/Web/Manifest).
pace.js](http:
//github.hubspot.com/pace/docs/welcome/)
outside of the bundled
code.
<script>
tag.
<script>
that declares global variables, you
also need to read the next section on
using them.
window
object, for example:
// eslint-disable-line
after it.
App.js](https:
//gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js)
redone using React Bootstrap.
npm install --save
flow-bin.
"flow":
"flow"
to the scripts
section of your package.json.
npm run flow init
to create a [.flowconfig
file](https:
//flowtype.org/docs/advanced-configuration.html)
in the root directory.
// @flow
to any files you want to type
check (for example, to src/App.js).
npm run flow
to check the files for type errors.
You can optionally use an IDE like
[Nuclide](https:
//nuclide.io/docs/languages/flow/) for
a better integrated experience. In the
future we plan to integrate it into
Create React App even more
closely.
src/App.js
and replace it with any of the
examples on its website. The [Basic
Example](https:
//reacttraining.com/react-router/web/example/basic)
is a good place to get started.
Note: this feature is available with[email protected]and higher.
NODE_ENV
defined for you, and any other
environment variables starting with REACT_APP_.
Note: You must create custom environment variables beginning withREACT_APP_. Any other variables exceptNODE_ENVwill be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https: //github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running.
process.env. For example, having an environment
variable named REACT_APP_SECRET_CODE
will be exposed in your JS as process.env.REACT_APP_SECRET_CODE.
NODE_ENV. You can read it from process.env.NODE_ENV. When you run npm start, it is always equal to 'development', when you run npm test
it is always equal to 'test', and when you run npm run build
to make a production bundle, it is
always equal to 'production'. You cannot override NODE_ENV
manually.
This prevents developers from
accidentally deploying a slow
development build to production.
<form>:
process.env.REACT_APP_SECRET_CODE
will be replaced with the current
value of the REACT_APP_SECRET_CODE
environment variable. Remember that
the NODE_ENV
variable will be set for you
automatically.
<input>, you will see its value set to abcdef, and the bold text will show the
environment provided when using npm start:
REACT_APP_SECRET_CODE
from the environment. In order to
consume this value, we need to have it
defined in the environment. This can
be done using two ways: either in your
shell or in a .env
file. Both of these ways are described
in the next few sections.
NODE_ENV
is also useful for performing actions
conditionally:
npm run build, the minification step will strip
out this condition, and the resulting
bundle will be smaller.
Note: this feature is available with[email protected]and higher.
REACT_APP_
in the public/index.html. For example:
NODE_ENV
and PUBLIC_URL), variable names must start
with REACT_APP_
to work.
.env
Note: this feature is available with[email protected]and higher.
.env
in the root of your project:
Note: You must create custom environment variables beginning withREACT_APP_. Any other variables exceptNODE_ENVwill be ignored to avoid [accidentally exposing a private key on the machine that could have the same name](https: //github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running.
.env
files should be
checked into source control (with the
exclusion of .env*.local).
.env
files can be used?
Note: this feature is available with[email protected]and higher.
.env: Default.
.env.local: Local overrides. This file is loaded for all
environments except
test.
.env.development, .env.test, .env.production: Environment-specific
settings.
.env.development.local, .env.test.local, .env.production.local: Local overrides of
environment-specific
settings.
npm start: .env.development.local, .env.development, .env.local, .env
npm run build: .env.production.local, .env.production, .env.local, .env
npm test: .env.test.local, .env.test, .env
(note .env.local
is missing)
Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https: //docs.travis-ci.com/user/environment-variables/) or [Heroku](https: //devcenter.heroku.com/articles/config-vars).
.env
Note: this feature is available with[email protected]and higher.
.env
file (using [dotenv-expand](https:
//github.com/motdotla/dotenv-expand)).
npm_package_version:
.env
file:
fetch()
API](https:
//developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
provided by the browser. Conveniently,
Create React App includes a polyfill
for fetch()
so you can use it without worrying
about the browser support.
fetch
function allows to easily makes AJAX
requests. It takes in a URL as an
input and returns a Promise
that resolves to a Response
object. You can find more information
about fetch
[here](https:
//developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).
fetch()
use Promises under the hood. You can
also use the [async / await](https:
//davidwalsh.name/async-await) syntax
to reduce the callback nesting.
fetch()
to access it.
Note: this feature is available with[email protected]and higher.
fetch('/api/todos')
without worrying about redirecting
them to another host or port during
development.
proxy
field to your package.json, for example:
fetch('/api/todos')
in development, the development server
will recognize that it's not a
static asset, and will proxy your
request to http:
//localhost:4000/api/todos
as a fallback. The development server
will only
attempt to send requests without text/html
in its Accept
header to the proxy.
proxy
only has effect in development (with npm start), and it is up to you to ensure that
URLs like /api/todos
point to the right thing in
production. You don't have to use
the /api
prefix. Any unrecognized request
without a text/html
accept header will be redirected to
the specified proxy.
proxy
option supports HTTP, HTTPS and
WebSocket connections. If the proxy
option is not
flexible enough for you, alternatively
you can:
proxy
option, you opt into a more strict set
of host checks. This is necessary
because leaving the backend open to
remote hosts makes your computer
vulnerable to DNS rebinding attacks.
The issue is explained in [this
article](https:
//medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a)
and [this issue](https:
//github.com/webpack/webpack-dev-server/issues/887).
localhost, but if you develop remotely like
[described here](https:
//github.com/facebookincubator/create-react-app/issues/2271),
you will see this error in the browser
after enabling the proxy
option:
Invalid Host header
.env.development
in the root of your project:
.env.development.local. Note that this is dangerous and
exposes your machine to remote code
execution from malicious
websites:
Note: this feature is available with[email protected]and higher.
proxy
option is not
flexible enough for you, you can
specify an object in the following
form (in package.json). You may also specify any
configuration value [http-proxy-middleware](https:
//github.com/chimurai/http-proxy-middleware#options)
or [http-proxy](https:
//github.com/nodejitsu/node-http-proxy#options)
supports.
text/html, which the standard proxy
option does not proxy.
package.json:
Note: this feature is available with[email protected]and higher.
HTTPS
environment variable to true, then start the dev server as usual
with npm start:
<meta>
Tags on the Server
<meta>
tags dynamic and reflect the current
URL. To solve this, we recommend to
add placeholders into the HTML, like
this:
index.html
into memory and replace __OG_TITLE__, __OG_DESCRIPTION__, and any other placeholders with
values depending on the current URL.
Just make sure to sanitize and escape
the interpolated values so that they
are safe to embed into HTML!
build
with a static hosting provider you can
use [react-snapshot](https:
//www.npmjs.com/package/react-snapshot)
or [react-snap](https:
//github.com/stereobooster/react-snap)
to generate HTML pages for each route,
or relative link, in your application.
These pages will then seamlessly
become active, or
"hydrated", when the
JavaScript bundle has loaded.
__SERVER_DATA__
with a JSON of real data right before
sending the response. The client code
can then read window.SERVER_DATA
to use it. Make sure to
[sanitize the JSON before sending it
to the client](https:
//medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to
XSS attacks.
Note: this feature is available with[email protected]and higher. >[Read the migration guide to learn how to enable it in older projects!](https: //github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030)
window
thanks to [jsdom](https:
//github.com/tmpvar/jsdom), they are
only approximations of the real
browser behavior. Jest is intended to
be used for unit tests of your logic
and your components rather than the
DOM quirks.
.js
suffix in __tests__
folders.
.test.js
suffix.
.spec.js
suffix.
.test.js
/ .spec.js
files (or the __tests__
folders) can be located at any depth
under the src
top level folder.
__tests__
folders) next to the code they are
testing so that relative imports
appear shorter. For example, if App.test.js
and App.js
are in the same folder, the test just
needs to import App from
'./App'
instead of a long relative path.
Colocation also helps find tests more
quickly in larger projects.
npm test, Jest will launch in the watch mode.
Every time you save a file, it will
re-run the tests, just like npm start
recompiles the code.
npm test, Jest will only run the tests
related to files changed since the
last commit. This is an optimization
designed to make your tests run fast
regardless of how many tests you have.
However it assumes that you don't
often commit the code that
doesn't pass the tests.
a
in the watch mode to force Jest to run
all tests.
it()
(or test()) blocks with the name of the test
and its code. You may optionally wrap
them in describe()
blocks for logical grouping but this
is neither required nor
recommended.
expect()
global function for making assertions.
A basic test could look like
this:
expect()
matchers supported by Jest are
[extensively documented here](https:
//facebook.github.io/jest/docs/en/expect.html#content).
You can also use [jest.fn()
and expect(fn).toBeCalled()](https:
//facebook.github.io/jest/docs/en/expect.html#tohavebeencalled)
to create "spies" or mock
functions.
src/components/MySample/test.tsx.
shallow
rendering:
ReactDOM.render(), this test only renders <App>
and doesn't go deeper. For
example, even if <App>
itself renders a <Button>
that throws, this test will pass.
Shallow rendering can be useful for
isolated unit tests, but it can create
some unexpected behavior. If
you're going to test using
Enzyme, unless you are testing very
basic functionality, we recommend you
use [full rendering with mount()](http:
//airbnb.io/enzyme/docs/api/mount.html).
Testing will be more consistent and
you can also use it for testing state
changes and component lifecycle.
expect()
and jest.fn()
for spies.
contains
code can be written more simply with
jest-enzyme.
jest-enzyme:
expect()
for assertions and jest.fn()
for spies. If you are having issues
with them please [file those against
Jest](https:
//github.com/facebook/jest/issues/new),
and we'll fix them. We intend to
keep making them better for React,
supporting, for example,
[pretty-printing React elements as
JSX](https:
//github.com/facebook/jest/pull/1566).
Note: this feature is available with[email protected]and higher.
src/setupTests.js
to your project. It will be
automatically executed before running
your tests.
src/setupTests.js
Note: Keep in mind that if you decide to "eject" before creatingsrc/setupTests.js, the resultingpackage.jsonfile won't contain any reference to it, so you should manually create the propertysetupTestFrameworkScriptFilein the configuration for Jest, something like the following:
1"jest": {23// ...4"setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.js"5}Copied!
it()
with xit()
to temporarily exclude a test from
being executed. Similarly, fit()
lets you focus on a specific test
without running any other tests.
npm test -- --coverage
(note extra --
in the middle) to include a coverage
report like this:
collectCoverageFrom](https:
//facebook.github.io/jest/docs/en/configuration.html#collectcoveragefrom-array)
coverageReporters](https:
//facebook.github.io/jest/docs/en/configuration.html#coveragereporters-array-string)
coverageThreshold](https:
//facebook.github.io/jest/docs/en/configuration.html#coveragethreshold-object)
snapshotSerializers](https:
//facebook.github.io/jest/docs/en/configuration.html#snapshotserializers-array-string)
npm test
runs the watcher with interactive CLI.
However, you can force it to run tests
once and finish the process by setting
an environment variable called CI.
npm run build
linter warnings are not checked by
default. Like npm test, you can force the build to perform
a linter warning check by setting the
environment variable CI. If any warnings are encountered
then the build fails.
CI
by default but you can do this
yourself too:
.travis.yml
file to your git
repository.
If you find yourself doing this often in development, please [file an issue](https: //github.com/facebookincubator/create-react-app/issues/new) to tell us about your use case because we want to make watcher the best experience and are open to changing how it works to accommodate more workflows.
package.json
of the generated project looks like
this:
--env=jsdom, and your tests will run
faster:
window
and document
ReactDOM.render()](https:
//facebook.github.io/react/docs/top-level-api.html#reactdom.render)
TestUtils.renderIntoDocument()](https:
//facebook.github.io/react/docs/test-utils.html#renderintodocument)
([a shortcut](https:
//github.com/facebook/react/blob/34761cf9a252964abfaab6faf74d473ad95d1f21/src/test/ReactTestUtils.js#L83-L91)
for the above)
mount()](http:
//airbnb.io/enzyme/docs/api/mount.html)
in [Enzyme](http:
//airbnb.io/enzyme/index.html)
TestUtils.createRenderer()](https:
//facebook.github.io/react/docs/test-utils.html#shallow-rendering)
(shallow rendering)
shallow()](http:
//airbnb.io/enzyme/docs/api/shallow.html)
in [Enzyme](http:
//airbnb.io/enzyme/index.html)
Note: debugging tests requires Node 8 or higher.
scripts
section in your project's package.json
debugger;
statements in any test and run:
inspect
on your process and a breakpoint will
be set at the first line of the react
script (this is done simply to give
you time to open the developer tools
and to prevent Jest from executing
before you have time to do so). Click
the button that looks like a
"play" button in the upper
right hand side of the screen to
continue execution. When Jest executes
the test that contains the debugger
statement, execution will pause and
you can examine the current scope and
call stack.
Note: the --runInBand cli option makes sure Jest runs test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time.
launch.json](https:
//code.visualstudio.com/docs/editor/debugging#_launch-configurations)
configuration file:
package.json:
sw-precache-webpack-plugin](https:
//github.com/goldhand/sw-precache-webpack-plugin)
is integrated into production
configuration, and it will take care
of generating a service worker file
that will automatically precache all
of your local assets and keep them up
to date as you deploy updates. The
service worker will use a [cache-first
strategy](https:
//developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network)
for handling all requests for local
assets, including the initial HTML,
ensuring that your web app is reliably
fast, even on a slow or unreliable
network.
registerServiceWorker()
from src/index.js.
registerServiceWorker()
in src/index.js
first by modifying the service worker
import:
unregister()
instead. After the user visits a page
that has unregister(), the service worker will be
uninstalled. Note that depending on
how /service-worker.js
is served, it may take up to 24 hours
for the cache to be invalidated.
localhost](http:
//stackoverflow.com/questions/34160509/options-for-testing-service-workers-via-http/34161385#34161385).
If your production web server
does not support HTTPS, then the
service worker registration will
fail, but the rest of your web
app will remain
functional.
npm run build. It's recommended that
you do not enable an
offline-first service worker in
a development environment, as it
can lead to frustration when
previously cached assets are
used and do not include the
latest changes you've made
locally.
npm run build) and run a simple http server
from your build directory. After
running the build script, create-react-app
will give instructions for one
way to test your production
build locally and the deployment
instructions have instructions
for using other methods. Be sure to always use an
incognito window to avoid
complications with your browser
cache.
service-worker.js
[with HTTP caching
disabled](http:
//stackoverflow.com/questions/38843970/service-worker-javascript-update-frequency-every-24-hours).
If that's not
possible—GitHub Pages, for
instance, does not allow you to
change the default 10 minute
HTTP cache lifetime—then be
aware that if you visit your
production site, and then
revisit again before service-worker.js
has expired from your HTTP
cache, you'll continue to
get the previously cached assets
from the service worker. If you
have an immediate need to view
your updated production
deployment, performing a
shift-refresh will temporarily
disable the service worker and
retrieve all assets from the
network.
src/registerServiceWorker.js, which demonstrates which
service worker lifecycle events
to listen for to detect each
scenario, and which as a
default, just logs appropriate
messages to the JavaScript
console.
eject
and then configure the [runtimeCaching](https:
//github.com/GoogleChrome/sw-precache#runtimecaching-arrayobject)
option in the SWPrecacheWebpackPlugin
section of webpack.config.prod.js.
public/manifest.json, that you can customize with details
specific to your web
application.
manifest.json
determines what icons, names, and
branding colors to use when the web
app is displayed. [The Web App
Manifest guide](https:
//developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/)
provides more context about what each
field means, and how your
customizations will affect your
users' experience.
package.json, add the following line to scripts:
npm run build
creates a build
directory with a production build of
your app. Set up your favorite HTTP
server so that a visitor to your site
is served index.html, and requests to static paths like /static/js/main.<hash>.js
are served with the contents of the /static/js/main.<hash>.js
file.
-p
or --port
flags.
build
folder with static assets is the only
output produced by Create React
App.
/todos/42
in your single-page app.
pushState
history API](https:
//developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries)
under the hood (for example, [React
Router](https:
//github.com/ReactTraining/react-router)
with browserHistory), many static file servers will
fail. For example, if you used React
Router with a route for /todos/42, the development server will respond
to localhost:3000/todos/42
properly, but an Express serving a
production build as above will
not.
/todos/42, the server looks for the file build/todos/42
and does not find it. The server needs
to be configured to respond to a
request to /todos/42
by serving index.html. For example, we can amend our
Express example above to serve index.html
for any unknown paths:
.htaccess
file in the public
folder that looks like this:
build
folder when you run npm run build.
/todos/42
will be handled correctly both in
development and in production.
/todos/42, by serving the cached copy of your index.html. This service worker navigation
routing can be configured or disabled
by ejecting and then modifying the [navigateFallback](https:
//github.com/GoogleChrome/sw-precache#navigatefallback-string)
and [navigateFallbackWhitelist](https:
//github.com/GoogleChrome/sw-precache#navigatefallbackwhitelist-arrayregexp)
options of the SWPreachePlugin
configuration.
/index.html. This may not work for client-side
routers which expect the app to be
served from /. Edit the web app manifest at public/manifest.json
and change start_url
to match the required URL scheme, for
example:
homepage
in your package.json, for example:
[email protected]^4, you can root <Link>s using the basename
prop on any <Router>. More information [here](https:
//reacttraining.com/react-router/web/api/BrowserRouter/basename-string).
For example:
Note: this feature is available with[email protected]and higher.
pushState
history API or not using client-side
routing at all, it is unnecessary to
specify the URL from which your app
will be served. Instead, you can put
this in your package.json:
index.html. You will then be able to move your
app from http: //mywebsite.com
to http:
//mywebsite.com/relativepath
or even http:
//mywebsite.com/relative/path
without having to rebuild it.
npm install -g firebase-tools. Sign up for a [Firebase
account](https:
//console.firebase.google.com) and
create a new project. Run firebase login
and login with your previous created
Firebase account.
firebase init
command from your project's root.
You need to choose the Hosting: Configure and deploy
Firebase Hosting sites
and choose the Firebase project you
created in the previous step. You will
need to agree with database.rules.json
being created, choose build
as the public directory, and also
agree to Configure as a single-page
app
by replying with y.
homepage
field to determine the root URL in the
built HTML file.
gh-pages
and add deploy
to scripts
in package.json
npm run build, you will see a cheat sheet with
instructions on how to deploy to
GitHub Pages.
package.json:
predeploy
script will run automatically before deploy
is run.
package.json
scripts to push deployments to master:
npm run deploy
gh-pages
gh-pages
branch:
CNAME
file to the public/
folder.
pushState
history API under the hood (for
example, React Router using browserHistory). This is because when there is a
fresh page load for a url like http:
//user.github.io/todomvc/todos/42, where /todos/42
is a frontend route, the GitHub Pages
server returns 404 because it knows
nothing of /todos/42. If you want to add a router to a
project hosted on GitHub Pages, here
are a couple of solutions:
hashHistory
for this effect, but the URL
will be longer and more verbose
(for example, http:
//user.github.io/todomvc/#/todos/42?_k=yknaj). [Read more](https:
//reacttraining.com/react-router/web/api/Router)
about different history
implementations in React
Router.
index.html
page with a special redirect
parameter. You would need to add
a 404.html
file with the redirection code
to the build
folder before deploying your
project, and you'll need to
add code handling the redirect
parameter to index.html. You can find a detailed
explanation of this technique
[in this guide](https:
//github.com/rafrex/spa-github-pages).
/dev/tty: No such a device or
address
or a similar error, try the
follwing:
git remote set-url origin
https:
//<user>:<token>@github.com/<user>/<repo>
.
npm run deploy again
npm run build
works locally but fails during deploy
via Heroku. Following are the most
common cases.
import
matches the one you see on your
filesystem or on GitHub.
MyDirectory
and mydirectory
are two distinct directories and thus,
even though the project builds
locally, the difference in case breaks
the import
statements on Heroku remotes.
.gitignore
or ~/.gitignore_global.
build
as the path to deploy.
npm run build
as the build command and build
as the publish directory
Deploy site
pushState, make sure to create a public/_redirects
file with the following rewrite
rules:
public
folder contents into the build
output.
now
to deploy your app for free.
now
command-line tool either via the
recommended [desktop
tool](https: //zeit.co/download)
or via node with npm install -g now.
npm run build.
cd build.
now --name
your-project-name
from within the build directory.
You will see a now.sh
URL in your output like
this:
npm install -g surge. Run the surge
command and log in you or create a new
account.
build
folder, for example:
pushState
API, you may want to rename the index.html
in your build folder to 200.html
before deploying to Surge. This
[ensures that every URL falls back to
that file](https:
//surge.sh/help/adding-a-200-page-for-client-side-routing).
none
to disable it
completely. If you
need to customize
the way the browser
is launched, you can
specify a node
script instead. Any
arguments passed to npm start
will also be passed
to this script, and
the url where your
app is served will
be the last
argument. Your
script's file
name must have the .js
extension.
localhost. You may use this
variable to specify
a different
host.
true, Create React App
will run the
development server
in https
mode.
package.json
(homepage). Normally, Create
React App ignores
the hostname. You
may use this
variable to force
assets to be
referenced verbatim
to the url you
provide (hostname
included). This may
be particularly
useful when using a
CDN to host your
application.
true, Create React App
treats warnings as
failures in the
build. It also makes
the test runner
non-watching. Most
CIs set this flag by
default.
none
to disable it completely. | |
CHOKIDAR_USEPOLLING |
true, the watcher runs in polling mode,
as necessary inside a VM. Use this
option if npm start
isn't detecting changes. | |
GENERATE_SOURCEMAP |
false, source maps are not generated for a
production build. This solves OOM
issues on some smaller machines. | |
NODE_PATH |
NODE_PATH
in Node.js](https:
//nodejs.org/api/modules.html#modules_loading_from_the_global_folders),
but only relative folders are allowed.
Can be handy for emulating a monorepo
setup by setting NODE_PATH=src. |
npm start
doesn't detect changes
npm start
is running, the browser should refresh
with the updated code. If this
doesn't happen, try one of the
following workarounds:
index.js
and you're referencing it
by the folder name, you [need to
restart the watcher](https:
//github.com/facebookincubator/create-react-app/issues/1164)
due to a Webpack bug.
.env
file in your project directory
if it doesn't exist, and
add CHOKIDAR_USEPOLLING=true
to it. This ensures that the
next time you run npm start, the watcher uses the polling
mode, as necessary inside a
VM.
npm test
hangs on macOS Sierra
npm test
and the console gets stuck after
printing react-scripts test --env=jsdom
to the console there might be a
problem with your [Watchman](https:
//facebook.github.io/watchman/)
installation as described in
[facebookincubator/create-react-app#713](https:
//github.com/facebookincubator/create-react-app/issues/713).
node_modules
in your project and running npm install
first. If it doesn't help, you
can try one of the numerous
workarounds mentioned in these
issues:
launchctl unload -F
~/Library/LaunchAgents/com.github.facebook.watchman.plist.
npm run build
exits too early
npm run build
can fail on machines with limited
memory and no swap space, which is
common in cloud environments. Even
with small projects this command can
increase RAM usage in your system by
hundreds of megabytes, so if you have
less than 1 GB of available memory
your build is likely to fail with the
following message:
The build failed because the process exited too early. This probably means the system ran out of memory or someone calledkill -9on the process.
npm run build
fails on Heroku
moment.locale()
with the locale name:
npm run build
fails to minify
module
field in package.json. Note that even if a library provides an
ES Modules version, it should
still precompile other ES6
features to ES5 if it intends to
support older browsers.
src/
folder and treat it as
application code.
react-scripts
and any other packages you need. [This
article](https:
//auth0.com/blog/how-to-configure-create-react-app/)
dives into how to do it in depth. You
can find more discussion in [this
issue](https:
//github.com/facebookincubator/create-react-app/issues/682).